﻿using System;
using System.Drawing;
using System.Drawing.Printing;
using System.Windows.Forms;
using DRHotel_v1.Classes;
using DRHotel_v1.Classes.DBManagers;

namespace DRHotel_v1.RoomAvaAndBooking
{
    public partial class CheckOutFrm : Form
    {
        public Customer cus;
        public Reservation res;
        public Room room;
        public DateTime now;
        private double amount = 0;
        private int days = 0;

        public CheckOutFrm()
        {
            InitializeComponent();
        }

        #region Form Load
        private void CheckOutFrm_Load(object sender, EventArgs e)
        {

            //load Room Info
            lblRoomID.Text = room.roomID.ToString();
            lblAdult.Text = res.numOfAdult.ToString();
            lblChildren.Text = res.numOfChildren.ToString();
            lblRoomType.Text = room.roomType;
            if (room.roomStatus.ToString().Equals("Occupied"))
            {
                cbbRoomStatus.SelectedIndex = 0;
            }
            else if (room.roomStatus.ToString().Equals("Vacant"))
            {
                cbbRoomStatus.SelectedIndex = 1;
            }
            else if (room.roomStatus.ToString().Equals("Clean"))
            {
                cbbRoomStatus.SelectedIndex = 2;
            }
            lblCheckInDate.Text = res.checkInDateTime.ToString();

            //load Customer Info
            lblICType.Text = cus.ICType.ToString();
            lblICNo.Text = cus.cusIC.ToString();
            lblFirstName.Text = cus.firstName.ToString();
            lblLastName.Text = cus.lastName.ToString();
            if (cus.gender)
            {
                lblGender.Text = "Male";
            }
            else
            {
                lblGender.Text = "Female";
            }
            lblCusType.Text = cus.cusType;
            lblPhoneNo.Text = cus.phoneNo.ToString();

            //DATE
            now = DateTime.Now;
            lblCheckOutTime.Text = now.ToString();

            //check if late checkout
            DateTime checker = new DateTime(2012, 8, 1, 12, 0, 0);
            if (now.TimeOfDay > checker.TimeOfDay)
            {
                lblLateCheckOut.Text = "Check Out Late!";
                lblLateCheckOut.ForeColor = Color.Red;
                cbxLate.Checked = true;
            }
            else
            {
                lblLateCheckOut.Text = "Check Out not late";
                lblLateCheckOut.ForeColor = Color.Green;
                cbxLate.Checked = false;
            }

            //label of Days Stayed
            double calDays = (now - res.checkInDateTime).TotalDays;
            days = Convert.ToInt32(Math.Ceiling(calDays));
            lblDaysStayed.Text = days.ToString();
            lblRoomRate.Text = room.roomRates.ToString();
            lblTotal.Text = amount.ToString();

            //checkbox for release reservation initial status
            cbxReleaseRes.Checked = false;
            cbxReleaseRes.ForeColor = Color.Black;
        }
        #endregion

        #region change room button clicked
        private void btnChange_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        #endregion

        #region check out button
        private void btnCheckOut_Click(object sender, EventArgs e)
        {
            //check if room status is changed
            if (cbbRoomStatus.Text.Equals("Occupied"))
            {
                MessageBox.Show("Please change room status!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            //update Customer info

            //Update Reservation class, set reservation status to Completed
            res.checkOutDateTime = Convert.ToDateTime(lblCheckOutTime.Text);
            res.resStatus = "Completed";

            //create CustomerBill class
            CustomerBill cb = new CustomerBill();
            cb.cusIC = cus.cusIC;
            cb.roomID = room.roomID;
            cb.roomRates = room.roomRates;
            if (cbxLate.Checked)
            {
                cb.ifLateCheckOut = true;
            }
            else
            {
                cb.ifLateCheckOut = false;
            }
            if (cbxReleaseRes.Checked == true)
            {
                cb.totalAmount = 0.00;
            }
            else
            {
                cb.totalAmount = Convert.ToDouble(lblTotal.Text);
            }

            //create Customer Payment
            if (rbnCreditCard.Checked)
            {
                if (tbxCardNo.Text.Length != 0)
                {
                    CustomerPayment cp = new CustomerPayment();
                    cp.cusIC = cus.cusIC;
                    cp.creditCardNum = Convert.ToInt64(tbxCardNo.Text);
                    cp.creditHolderName = tbxNameOnCard.Text;
                    cp.creditExpiryDate = tbxExpDate.Text;
                    long cCardNo = Convert.ToInt64(tbxCardNo.Text);
                    if (RoomAvaAndBookingDBManager.SearchPaymentByCardNo(cCardNo) == 0)
                    {
                        if (RoomAvaAndBookingDBManager.InsertCustomerPayment(cp) == 0)
                        {
                            MessageBox.Show("Cannot insert payment info into Database!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                    }
                    else
                    {
                        if (RoomAvaAndBookingDBManager.UpdateCustomerPayment(cp) == 0)
                        {
                            MessageBox.Show("Cannot update payment info into Database!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Card Number is empty!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                
            }

            //Update Database
            if (RoomAvaAndBookingDBManager.UpdateReservationInfo(res) == 0)
            {
                MessageBox.Show("Cannot update Reservation info!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else if (RoomAvaAndBookingDBManager.UpdateRoomStatus(lblRoomID.Text, cbbRoomStatus.Text) == 0)
            {
                MessageBox.Show("Cannot update room status!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else if (RoomAvaAndBookingDBManager.InsertCustomerBill(cb) == 0)
            {
                MessageBox.Show("Cannot insert customer bill into database!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else
            {
                MessageBox.Show("Check Out Successful!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                btnInvoice.Visible = true;
                return;
            }


        }
        #endregion

        #region input validation
        //validate credit card input, only allow numbers 
        private void tbxCardNo_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
                errorProvider1.SetError(tbxCardNo, "Only numbers may be entered here");
            }
            else
            {
                errorProvider1.SetError(tbxCardNo, String.Empty);
            }
        }

        //validate exp date input
        private void tbxExpDate_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '/')
            {
                e.Handled = true;
                errorProvider1.SetError(tbxExpDate, "Please follow the example (MM/YY)");
            }
            else
            {
                errorProvider1.SetError(tbxExpDate, String.Empty);
            }
        }

        private void tbxNameOnCard_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back || e.KeyChar == (char)Keys.Space))
            {
                e.Handled = true;
                errorProvider1.SetError(tbxNameOnCard, "Invalid name format");
            }
            else
            {
                errorProvider1.SetError(tbxNameOnCard, String.Empty);
            }
        }

        private void tbxExtraFee_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
            {
                e.Handled = true;
            }
        }
        #endregion

        #region calculate button
        private void btnCalculate_Click(object sender, EventArgs e)
        {
            amount += room.roomRates * days;
            if (cbxLate.Checked)
            {
                amount += room.roomRates;
            }
            if (tbxExtraFee.TextLength != 0)
            {
                double extra = Convert.ToDouble(tbxExtraFee.Text);
                amount += extra;
            }
            lblTotal.Text = amount.ToString();
            amount = 0;
        }
        #endregion

        #region edit customer info button
        private void btnEditCusInfo_Click(object sender, EventArgs e)
        {
            CustomerUpdateFrm frm = new CustomerUpdateFrm();
            frm.cusIC = lblICNo.Text;
            frm.Show();
        }
        #endregion

        #region change check box Release reservation status
        private void cbxReleaseRes_CheckedChanged(object sender, EventArgs e)
        {
            if (cbxReleaseRes.Checked == true)
            {
                cbxReleaseRes.ForeColor = Color.Red;
            }
        }
        #endregion

        #region display credit card info field
        private void rbnCreditCard_CheckedChanged(object sender, EventArgs e)
        {
            groupBoxCardInfo.Visible = true;
        }
        private void rbnCash_CheckedChanged(object sender, EventArgs e)
        {
            groupBoxCardInfo.Visible = false;
        }
        #endregion

        #region Print Invoice

        private PrintDocument printDocument1 = new PrintDocument();
        private PrintPreviewDialog printPreviewDialog1 = new PrintPreviewDialog();

        private void btnInvoice_Click(object sender, EventArgs e)
        {
            string roomNo = lblRoomID.Text; ;
            string checkInDate = lblCheckInDate.Text;
            string checkOutDate = lblCheckOutTime.Text;
            string adult = lblAdult.Text;
            string children = lblChildren.Text;
            string roomRate = lblRoomRate.Text;
            string days = lblDaysStayed.Text;
            string ifLateCheckOut = lblLateCheckOut.Text;
            string extraFee = tbxExtraFee.Text;
            string total = lblTotal.Text;

            InvoiceFrm frm = new InvoiceFrm();
            frm.roomNo = roomNo;
            frm.checkInDate = checkInDate;
            frm.checkOutDate = checkOutDate;
            frm.adult = adult;
            frm.children = children;
            frm.roomRate = roomRate;
            frm.days = days;
            frm.ifLateCheckOut = ifLateCheckOut;
            frm.extraFee = extraFee;
            frm.total = total;
            frm.Show();
            
            //printDocument1.Print();
        }

        Bitmap memoryImage;
        private void CaptureScreen()
        {
            Graphics myGraphics = this.CreateGraphics();
            Size s = this.Size;
            memoryImage = new Bitmap(s.Width, s.Height, myGraphics);
            Graphics memoryGraphics = Graphics.FromImage(memoryImage);
            memoryGraphics.CopyFromScreen(this.Location.X, this.Location.Y, 0, 0, s);
        }

        private void printDocument1_PrintPage(System.Object sender,
               System.Drawing.Printing.PrintPageEventArgs e)
        {
            e.Graphics.DrawImage(memoryImage, 0, 0);
        }


        #endregion

    }
}
